<?php

//namespace SimpleChat;

use Workerman\Worker;

require_once '../global_config.php';
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/26
 * Time: 20:52
 */
//一个简单的即时聊天入口文件
$global_uid = 0;
//当客户端连接上来时分配Uid 并保持连接 并且通知所有客户端
function handle_connection($connection)
{
    global $text_worker, $global_uid;
    //为这个连接分配一个uid
    $connection->uid = ++$global_uid;
    foreach ($text_worker->connections as  $conn) {
        $conn->send("user[{$connection->uid}] login");
    }
}

//当客户端发送来消息过来时并转发给所有人
function handle_message($connection, $data)
{
    global $text_worker;
    foreach ($text_worker->connections as $conn) {
        $conn->send("user[{$connection->uid}] said:$data");
    }
}

//当客户端断开时，广播给所有客户端
function handle_close($connection)
{
    global $text_worker;
    foreach ($text_worker->connections as  $conn) {
        $conn->send("user[{$connection->uid}] logout");
    }
}

//创建一个文本协议的Worker监听2348端口
$text_worker = new Worker('text://0.0.0.0:2348');
//只启动一个进程 这样方便客户端之间的传输数据
$text_worker->count = 1;
$text_worker->onConnect = 'handle_connection';
$text_worker->onMessage = 'handle_message';
$text_worker->onClose = 'handle_close';
Worker::runAll();